#!/usr/bin/env node

var fs = require('fs')
  , path  = require('path')
  , view  = require('./lib/view')
  , obj  = require('./lib/obj')
  , actors  = require('./lib/actors')
  , compiler = require('./lib/compiler')
  , slide = require('slide')
  , chain = slide.chain
  , asyncMap = slide.asyncMap
  ;

var rootd = path.resolve(__dirname, '..')
  , env =
    { layout: rootd + '/doc/layout.ejs'
    , apple_logo: rootd + '/doc/pages/images/apple_logo.svg'
    , ubuntu_logo: rootd + '/doc/pages/images/ubuntu_logo.svg'
    , freebsd_logo: rootd + '/doc/pages/images/freebsd_logo.svg'
    , windows_logo: rootd + '/doc/pages/images/windows_logo.svg'
    }

function done() {
  console.log('============= DONE ===============');
  console.log(arguments);
  console.log(env);
  console.log('==================================');
}

var render = compiler.compiler(view.render, 'ejs', env)
  ;

function configure(cb) {
  env.src = compiler.src;
  env.dst = compiler.dst;
  env.outputDir = rootd + '/out/pages';
  cb()
};

var git = actors.commandActor('git');

console.log('rootd', rootd);

chain( [ [ actors.loadEnv, env ]
       , [ configure ]
       //, [ git, ['clone', '-b', 'ci-build', 'git://github.com/agnat/node_mdns.git'
       //        , rootd + '/out/ci-build'] ]
       , [ actors.glob, rootd + '/out/ci-build/builds/*.json' ]
       , [ load_builds, chain.last ]
       , [ render_status_page, chain.last]
       ]
     , done
     );

function load_builds(files, cb) {
  asyncMap(files, load_build, function(error, builds) {
    var result = {}
    builds.forEach(function(b) { result[b.id] = b; b.timestamp = parseInt(b.timestamp) });
    cb(error, result);
  });
}

function render_status_page(builds, cb) {
  var ids = Object.keys(builds).sort(function(a, b) { return b - a })
    , latest = builds[ids[0]]
    , history = []
    , latest_stages = []
    , versions = {}
    , os = {}
    ;
  for (var i = 1; i < ids.length; ++i) {
    history.push(builds[ids[i]]);
  }
  for (var stage in latest.stages) {
    var tokens = stage.split('-')
      , node = tokens[0]
      , build_system = tokens[2]
      ;
    node = node.replace(/(\d+)_(\d+)/, "$1.$2").replace(/_/, ' ');
    var version = node.split(' ')[1];
    latest.stages[stage].node_version = version;
    version += '-' + build_system;
    latest.stages[stage].key = version;
    versions[version] = {name: latest.stages[stage].node_version, sub: build_system};
    os[latest.stages[stage].os] = {name: latest.stages[stage].os};
  }
  Object.keys(versions).forEach(function(v, i) { versions[v].idx = i});
  Object.keys(os).forEach(function(o, i) { os[o].idx = i; });
  var version_count = Object.keys(versions).length;
  Object.keys(os).forEach(function(o,i) {
    latest_stages[i] = new Array(version_count);
  });
  for (var stage in latest.stages) {
    var s = latest.stages[stage];
    latest_stages[versions[s.key].idx][os[s.os].idx] = s;
  }

  console.log('versions:', versions, 'os:', os);

  render( rootd + '/doc/build/status.ejs'
        , rootd + '/out/pages/build/status.html'
        , { locals:
            { latest: latest
            , history: history
            , latestStages: latest_stages
            , versions: versions
            , os: os
            , logos:
              { macosx: env.apple_logo
              , linux: env.ubuntu_logo
              , freebsd: env.freebsd_logo
              , win32: env.windows_logo
              }
            }
          }
        , cb
        )
}

function load_build(f, cb) {
  fs.readFile(f, function loaded(error, buffer) {
    cb(error, buffer ? JSON.parse(buffer) : buffer)
  })
}

// vim: filetype=javascript :
